﻿using Cysharp.Threading.Tasks;
using YooAsset;

namespace Client.Base
{
    public class FsmRequestPackageVersion : PatchState
    {
        private bool isSucc = true;

        public FsmRequestPackageVersion(PatchProcess procedure) : base(procedure)
        {
        }

        public override async void OnEnter()
        {
            this.Log("[Patch] FsmRequestPackageVersion.");
            isSucc = true;
            var packages = YAPackageInfo.Setting.packages;
            for (int i = 0; i < packages.Length; i++)
                await UpdatePackageVersion(packages[i].packageName);
            if (!isSucc)
            {
                Process.Call(Event_PatchError.EVENT_PATCHERROR, new Event_PatchError
                {
                    status = 1402,
                    message = $"更新本地资源版本失败!"
                });
                return;
            }
            Process.TryTransition<FsmUpdatePackageManifest>();
        }

        private async UniTask UpdatePackageVersion(string packageName)
        {
            var package = YooAssets.GetPackage(packageName);
            var operation = package.RequestPackageVersionAsync();
            await operation.ToUniTask();
            if (operation.Status != EOperationStatus.Succeed)
            {
                isSucc = false;
                this.Log($"[Patch]: Fail ！-> pk:{package} , error : {operation.Error}");
            }
            else
            {
                Process.SetPackageVersion(packageName, operation.PackageVersion);
            }
        }
    }

}
